package cn.stylefeng.guns.modular.info.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.SystemClock;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.stylefeng.guns.modular.info.entity.AicaiGame;
import cn.stylefeng.guns.modular.info.mapper.AicaiGameMapper;
import cn.stylefeng.guns.wechat.UploadMeida;
import cn.stylefeng.guns.wechat.WeChatMsgSend;
import cn.stylefeng.guns.wechat.WeChatUrlData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: football_manage
 * @description:
 * @author: xiesm
 * @create: 2021-07-14 13:42
 **/
@Service
public class AicaiService {
    @Autowired(required = false)
    private AicaiGameMapper aicaiGameMapper;

    public void searchMatch(String date) throws IOException {
        List<AicaiGame> games = aicaiGameMapper.selectList(null);
        Set<Integer> matchIds = games.stream().map(game -> game.getId()).collect(Collectors.toSet());
        String format = "yyyy-MM-dd";
        DateTime dateTime = DateUtil.parse(date, format);
        long day = DateUtil.betweenDay(dateTime, new Date(), true);
        for (int i = 0; i < day; i++) {
            String dateStr = DateUtil.format(DateUtil.offsetDay(dateTime, i), format);
            searchMatch(dateStr, matchIds);
        }
    }

    private void searchMatch(String date, Set<Integer> matchIds) throws IOException {
        String url = "https://live.aicai.com/static/no_cache/league/zc/jsbf/ttyq2020/jczq/jsbf_{}.json?v=1626236613817";
        url = StrUtil.format(url, date);

        JSONObject data = sendAicaiGet(url);

        JSONArray matchList = data.getJSONArray("matchList");
        if (matchList == null) {
            return;
        }
        for (int i = 0; i < matchList.size(); i++) {
            JSONObject match = matchList.getJSONObject(i);
            int matchId = match.getIntValue("matchId");
            if (!matchIds.add(matchId)) {
                continue;
            }

            AicaiGame game = new AicaiGame();
            String matchNo = match.getString("matchNoCn");
            game.setMatchCn(matchNo.substring(0, 2));
            game.setMatchNo(matchNo.substring(2));

            game.setLeagueName(match.getString("leagueName"));

            String matchDate = match.getString("matchDate");
            String matchTime = match.getString("matchTime");
            DateTime dateTime = DateUtil.parse(StrUtil.format("{} {}:00", matchDate, matchTime), "yyyy-MM-dd HH:mm:ss");
            game.setDate(dateTime);

            game.setTeamAName(match.getString("homeName"));
            game.setTeamBName(match.getString("awayName"));

            try {
                game.setScore(match.getJSONArray("score").getString(1));
            } catch (Exception e) {
                e.printStackTrace();
            }

            game.setPeriod(date);
            game.setId(matchId);
            try {
                JSONObject params = new JSONObject();
                params.put("apiName", "getMatchEvent");
                params.put("matchId", matchId);
                params.put("timestamp", SystemClock.now());

                url = "https://m.ttyingqiu.com/sportdata/f";

                data = sendAicai(params, url);
                JSONArray eventList = data.getJSONArray("eventList");
                boolean boo = false;
                for (int j = 0; j < eventList.size(); j++) {
                    JSONObject event = eventList.getJSONObject(j);
                    if (Objects.equals("8", event.getString("eventType"))) {
                        boo = true;
                    }
                }
                game.setOwnGoal(boo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ThreadUtil.sleep(250);
            aicaiGameMapper.insert(game);
        }
    }

    public JSONObject sendAicai(JSONObject params, String url) {
        String res = HttpUtil.createPost(url).body(params.toJSONString())
                .contentType(ContentType.JSON.toString()).execute().body();
        return JSONObject.parseObject(res);
    }

    public JSONObject sendAicaiGet(String url) {
        System.out.println("url=" + url);
        try {
            String res = HttpUtil.createGet(url).execute().body();
            return JSONObject.parseObject(res);
        } catch (Exception e) {
            return new JSONObject();
        }
    }

    public void aicaiOwnGoalReport() throws Exception {
        String date = DateUtil.format(DateUtil.offsetDay(new Date(), -1), "yyyy-MM-dd");
        QueryWrapper query = new QueryWrapper();
        query.eq("period", date);
        query.orderByAsc("match_no");
        List<AicaiGame> matchs = aicaiGameMapper.selectList(query);
        ExcelWriter writer = ExcelUtil.getWriter();

        writer.addHeaderAlias("period", "日期");
        writer.addHeaderAlias("leagueName", "联赛");
        writer.addHeaderAlias("teamAName", "主队");
        writer.addHeaderAlias("teamBName", "客队");
        writer.addHeaderAlias("matchCn", "星期");
        writer.addHeaderAlias("matchNo", "编号");
        writer.addHeaderAlias("ownGoal", "结果");

        String path = System.getProperty("java.io.tmpdir");
        File tempFile = new File(StrUtil.format("{}{}.xls", path, SystemClock.now()));

        List<Map<String, Object>> lists = new ArrayList<>();
        matchs.stream().forEach(match -> {
            Map<String, Object> map = new HashMap<>();
            map.put("period", match.getPeriod());
            map.put("leagueName", match.getLeagueName());
            map.put("teamAName", match.getTeamAName());
            map.put("teamBName", match.getTeamBName());
            map.put("matchCn", match.getMatchCn());
            map.put("matchNo", match.getMatchNo());
            map.put("ownGoal", String.valueOf(match.getOwnGoal()));
            lists.add(map);
        });

        writer.write(lists);
        writer.setColumnWidth(0, 20);
        writer.setColumnWidth(1, 20);
        writer.setColumnWidth(2, 20);

        writer.flush(tempFile);

        UploadMeida uploadMeida = new UploadMeida();
        JSONObject jsonObject = uploadMeida.UploadMeida("file", tempFile);

        Object media_id = jsonObject.get("media_id");
        WeChatMsgSend swx = new WeChatMsgSend();
        String token = swx.getToken("wwd10c4d16064ab819", "ZxZ9-gsMY7_0hq7l_KUo-9mylpItk95xaLriUwVLkTg");
        String postdata = swx.createpostdata("@all", "file", 1000005, "media_id", media_id);
        swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, token);
    }
}
